package com.lx.mobileplayer.mvp.view.activity

import com.lx.mobileplayer.utils.AppManager
import com.lx.mobileplayer.utils.FragmentFactory
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.tool_bar.*
import com.lx.mobileplayer.R
import com.lx.mobileplayer.utils.LogUtil
import com.lx.mobileplayer.utils.ToastUtil


class MainActivity : ToolbarActivity() {

    var mCurrentItem=0

    private val mBottomBar by lazy{
        bottom_bar
    }

    override fun getLayoutId(): Int {
        return R.layout.activity_main
    }

    override fun initToolbar() {
        toolbar.title="手机影音"
        toolbar.inflateMenu(R.menu.menu_home)

        toolbar.setOnMenuItemClickListener {
            if(it.itemId== R.id.setting){
                AppManager.goSettingActivity(getMContext())
            }

            true
        }
    }

    override fun initView() {
        super.initView()

        //默认展示首页
        changeFragment(0)

        mBottomBar.setOnTabSelectListener { tabId->

            if(mBottomBar.currentTabId!=tabId){

                LogUtil.d("getTabPosition(tabId)=${getTabPosition(tabId)}")

                changeFragment(getTabPosition(tabId))

            }
        }
    }

    /**
     * 切换Fragment
     */
    @Synchronized
    fun changeFragment(index: Int) {

        val fragmentTranbein = supportFragmentManager.beginTransaction()
        if (mCurrentItem !== -1) {
            val outFragment = FragmentFactory.instance.getFragment(mCurrentItem)

            outFragment.onPause()//2016.9.30 添加主要解决页面切换的问题
            fragmentTranbein.hide(outFragment)
        }
        mCurrentItem = index
        val inFragment =  FragmentFactory.instance.getFragment(mCurrentItem)
        if (!inFragment.isAdded()) {
            fragmentTranbein.add(R.id.fl_content, inFragment)

        }
        fragmentTranbein.show(inFragment)
        fragmentTranbein.commitAllowingStateLoss()
    }

    fun getTabPosition(tabId:Int):Int{
        return when(tabId){
            com.lx.mobileplayer.R.id.tab_01-> 0
            com.lx.mobileplayer.R.id.tab_02-> 1
            com.lx.mobileplayer.R.id.tab_03-> 2
            com.lx.mobileplayer.R.id.tab_04-> 3
            else -> 0
        }
    }

    override fun onBackPressed() {

        finish()
    }
}

